﻿/**
 * This is a softerware for get 51 album photos.
 * @auther William 2012-3-27
 * 
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Winista.Text.HtmlParser;
using Winista.Text.HtmlParser.Lex;
using Winista.Text.HtmlParser.Util;
using Winista.Text.HtmlParser.Tags;
using Winista.Text.HtmlParser.Filters;
using Winista.Text.HtmlParser.Nodes;
using System.Net;

namespace DownAlbum
{
    public partial class DownAlbum : Form
    {
        IList<int> start = new List<int>();
      

        public DownAlbum()
        {
            InitializeComponent();
        }
        //获得HTML页面并解析
        public void parseHTML11()
        {
            string url = "http://home.51.com/" + username.Text + "/photo";
            Uri uri = new Uri(url);

            WebClient webClient = new WebClient();

            webClient.Encoding = System.Text.Encoding.Default;

            string html = webClient.DownloadString(url);

            //提取相册名字

         
            ////分析
            //#region 分析网页html节点
             Lexer lexer = new Lexer(html);
             Parser parser = new Parser(lexer);

             NodeList htmlNodes = parser.Parse(new 
                 NodeClassFilter(typeof(Winista.Text.HtmlParser.Tags.Div)));

             if (htmlNodes.Count == 0)
                 MessageBox.Show("没有符合要求的节点");
             else
             {
                 //查找节点

                 ITag myTag = null;
                 for (int i = 0; i < htmlNodes.Count; i++)
                 {
                     ITag tag = (htmlNodes[i] as ITag);
                     if (tag.GetAttribute("ID") == "photo_box_body")
                     {
                         myTag = tag;
                         break;
                     }

                 }

                 NodeList divList = myTag.Children;
                 INode tableNode = divList[1];   // get table
                 NodeList tableList = tableNode.Children;  //获取到table的栏 tr

                 //tr 的数组

                 for (int i = 0; i <= tableList.Count; i++)
                 {
                     //针对tr标签下内容进行处理   
                     /*
                     <td>
                      <div class="pic">
                       <div>
                         <a href="/lp88513/photo/group/125212">
                           <img width="130" onload="newsphotoresize(this,130);" src="http://static.51img1.com/v3/photo/images/default_cover.jpg">
                         </a>
                       </div>
                      </div>
                      <h4>
                      <a href="/lp88513/photo/group/125212">亲人的照片</a>
                       </h4>
                         <p>(共0张照片)</p>
                     </td>
                      */
                     NodeList td = tableList[i].Children; //td序列
                     string tdHTML = td.ToHtml();
                     Parser p = Parser.CreateParser(tdHTML, null);

                     //处理td序列

                     NodeList n = p.ExtractAllNodesThatMatch(new TagNameFilter("a"));//匹配链接标签

                     ITag tagTmp = (n[2] as ITag);    //获取的相册地址
                     string photo_url = "http://home.51.com" + tagTmp.GetAttribute("href");  //相册的地址
                     string photo_html = webClient.DownloadString(photo_url); 

                     //处理相册中的表格序列
                     p = Parser.CreateParser(photo_html,null);
                     NodeList nodeTable = p.ExtractAllNodesThatMatch(new TagNameFilter("table"));//匹配链接标签table

                     if (nodeTable.Count > 0)
                     {
                         INode albumNode = nodeTable[0];  //获取第一个table，也仅此一个

                         NodeList photo_url_list = (Parser.CreateParser(albumNode.ToHtml(), null))
                               .ExtractAllNodesThatMatch(new TagNameFilter("img"));         //解析出包含每个照片的url
                         // MessageBox.Show(photo_url_list.Count.ToString());
                         ITag photo_tag = null;
                         for (int k = 0; k < photo_url_list.Count; k++)
                         {
                             photo_tag = photo_url_list[k] as ITag;
                             webClient.DownloadFile(new Uri(photo_tag.GetAttribute("src").ToString()), "d://" + k + ".jpg");
                         }


                     }
                     
                 }
             }
                  
        }

       private ITag findHtmlNode(INode htmlNode)
        {
            if (htmlNode is ITag)
            {
                ITag tag = (htmlNode as ITag);
                if (!tag.IsEndTag())
                {
                    if (tag.Attributes != null && tag.Attributes.Count > 0)
                    {
                        if (tag.Attributes["ID"] != null)
                        {
                            return tag;
                        }

                    }
                }
            }
            
            return null;
        }


        private void paserData(INode node)
        {
            ITag tag = getTag(node);
            if (tag != null && !tag.IsEndTag())
            {

                object oId = tag.GetAttribute("id");
                object oName = tag.GetAttribute("name");
                object oClass = tag.GetAttribute("class");
               
            }
        }
    ////////////////////////////////////////////////////////////////

        private ITag getTag(INode node)
        {
            if (node == null)
                return null;
            return node is ITag ? node as ITag : null;
        }

        //验证文本框中信息有效性
        private bool isValide()
        {
            if (username.Text.Equals(""))
            {
                MessageBox.Show("用户名不能为空！");
                return true;
            }
            else if (address.Text.Equals(""))
            {
                MessageBox.Show("下载地址不能为空！");
                return true;
            }
            return false;
        }

       //解析HTML
        private string parseHTMLtoString(string url)
        {
           //添加异常处理
            Uri uri = new Uri(url);
            WebClient webClient = new WebClient();
            webClient.Encoding = System.Text.Encoding.Default;
            string html = webClient.DownloadFile(url);
            if (html.Length > 0)
                return html;
            else
                return "failed";

        }
        
        //获取所有相册
        private List<string> getAllAlbums(string username)
        {
            List<string> albums = new List<string>();
            //解析Html  http://home.51.com/lp88513/photo
            string url = "http://home.51.com/" + username.Text + "/photo";
            string albumsString = parseHTMLtoString(url);
            if(!albumsString.Equals("failed"))            //判断是否解析成功
            {
                /* 针对table的相册列表
                 <div id="photo_catalog_body" class="item_body photo_body">
                 <table id="mll" align="center" width="100%" cellspacing="0" cellpadding="0" border="0">
                */
             Parser p = Parser.CreateParser(albumsString, null);
             NodeList albumNodeList = p.ExtractAllNodesThatMatch(new TagNameFilter("div"));//匹配标签
             // 依据id = "photo_catalog_body" 找到相应的div
                 INode tempNode = new Div();
                  
                albumNodeList.SearchFor().KeepAllNodesThatMatch

                   



             ITag tagTmp = (n[2] as ITag);    //获取的相册地址
             string photo_url = "http://home.51.com" + tagTmp.GetAttribute("href");  //相册导航的地址
             string photo_html = webClient.DownloadString(photo_url); 

                

            }

        }
        
        private void download_Click(object sender, EventArgs e)
        {
            //验证信息有效性
            if(isValide())
                  return;
            //获取所有相册填入CheckedListBox中

            parseHTML();
                    
        }

        private void albumChoice_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
